package com.kelvin.backend.okhttp.config;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * <p>Package: com.dl.zofund.config.okhttp</p>
 * <p>Title: OkHttpConfig</p>
 * <p>Description: okhttp连接配置</p>
 *
 * @author Kingdom.Chen
 * @datetime 2019/9/24 17:48
 */
@Configuration
public class OkHttpConfig {

    private static final Logger log = LoggerFactory.getLogger(OkHttpConfig.class);

    @Value("${okhttp.connect-timeout:30}")
    private Integer connectTimeout;

    @Value("${okhttp.read-timeout:30}")
    private Integer readTimeout;

    @Value("${okhttp.write-timeout:30}")
    private Integer writeTimeout;

    @Value("${okhttp.max-idle-connections:200}")
    private Integer maxIdle;

    @Value("${okhttp.keep-alive-duration:300}")
    private Integer keepAlive;

    @Bean
    public OkHttpClient okHttpClient() {
        log.info("[OkHttpConfig] 初始化客户端 -> OkHttpClient");
        return new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory(), x509TrustManager())
                // 当连接失败的是否，重新连接尝试
                .retryOnConnectionFailure(true)
                .connectionPool(pool())
                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                .hostnameVerifier((hostname, session) -> true)
                .build();

    }

    @Bean
    public X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }

    @Bean
    public SSLSocketFactory sslSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            log.error("[sslSocketFactory]出现异常 -> ", e);
        }

        return null;
    }

    @Bean
    public ConnectionPool pool() {
        return new ConnectionPool(maxIdle, keepAlive, TimeUnit.SECONDS);
    }
}
